import user from "@/store/modules/user";
import local from "@utils/store/localStorage";
import MD5 from "js-md5";

/**
 * 获取浏览器唯一ID标识
 */
function getBrowserUnionId() {
  let result = "";
  let canvas = document.createElement("canvas");
  canvas.width = 200;
  canvas.height = 20;
  canvas.style.display = "inline";
  let ctx = canvas.getContext("2d");
  ctx.rect(0, 0, 10, 10);
  ctx.rect(2, 2, 6, 6);
  result +=
    "canvas winding:" +
    (ctx.isPointInPath(5, 5, "evenodd") === false ? "yes" : "no");
  ctx.textBaseline = "alphabetic";
  ctx.fillStyle = "#f60";
  ctx.fillRect(125, 1, 62, 20);
  ctx.fillStyle = "#069";
  ctx.font = "11pt no-real-font-123";
  ctx.fillText("Cwm fjordbank glyphs vext quiz, \ud83d\ude03", 2, 15);
  ctx.fillStyle = "rgba(102, 204, 0, 0.2)";
  ctx.font = "18pt Arial";
  ctx.fillText("Cwm fjordbank glyphs vext quiz, \ud83d\ude03", 4, 45);
  ctx.globalCompositeOperation = "multiply";
  ctx.fillStyle = "rgb(255,0,255)";
  ctx.beginPath();
  ctx.arc(50, 50, 50, 0, Math.PI * 2, true);
  ctx.closePath();
  ctx.fill();
  ctx.fillStyle = "rgb(0,255,255)";
  ctx.beginPath();
  ctx.arc(100, 50, 50, 0, Math.PI * 2, true);
  ctx.closePath();
  ctx.fill();
  ctx.fillStyle = "rgb(255,255,0)";
  ctx.beginPath();
  ctx.arc(75, 100, 50, 0, Math.PI * 2, true);
  ctx.closePath();
  ctx.fill();
  ctx.fillStyle = "rgb(255,0,255)";
  ctx.arc(75, 75, 75, 0, Math.PI * 2, true);
  ctx.arc(75, 75, 25, 0, Math.PI * 2, true);
  ctx.fill("evenodd");
  if (canvas.toDataURL) result += ";canvas fp:" + canvas.toDataURL();
  let hash = 0;
  if (result.length > 0) {
    for (let i = 0; i < result.length; i++) {
      const char = result.charCodeAt(i);
      hash = (hash << 5) - hash + char;
      hash = hash & hash; // Convert to 32bit integer
    }
  }
  return MD5(hash + "");
}

const config = {
  state: {
    rn: local.get("RN") || "en",
    identityId: getBrowserUnionId()
  },
  mutations: {
    SET_RN(state, rn) {
      state.rn = rn;
      local.set("RN", rn);
    }
  },
  actions: {
    changeRN({ commit, state }, rn) {
      return new Promise((resolve, reject) => {
        if (user.state.token) {
          reject("当前未接入API");
        } else {
          commit("SET_RN", rn);
          resolve(rn);
        }
      });
    }
  }
};
export default config;
